package com.lngsyz.ywtb.pay;


import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lngsyz.ywtb.pay.entity.SealRefundHandleVO;
import com.lngsyz.ywtb.pay.entity.SealTradeHandleVO;
import com.lngsyz.ywtb.pay.entity.SealTradeMainInfoVO;
import com.lngsyz.ywtb.pay.entity.SealTradeQueryVO;
import com.lngsyz.ywtb.pay.entity.SealTradeTrackVO;
import com.lngsyz.ywtb.pay.exception.RequestSystemException;
import com.lngsyz.ywtb.pay.utils.NumUtils;
import com.lngsyz.ywtb.pay.utils.SM2Util;
import com.lngsyz.ywtb.util.BusinessLicenseValidator;
import com.lngsyz.ywtb.util.HttpUtils;

/**
 *
 * @author: 朱志红
 * @date: 2020年10月29日
 * @version: 1.0
 */

public class PaySdk {
	
	//private static final String _host = "https://iaip.lngsyz.com";
	private static final String _host = "http://120.201.201.55:9001";

	private static final String CREATE_SEAL_TRANSACTION_ORDER_URL = "/api/v1/sealUnifyPay/createSealTrade";

	private static final String QUERY_TRANSACTION_ORDER_RESULT_URL = "/api/v1/sealUnifyPay/trackSealTrade";

	private static final String QUERY_HISTORICAL_TRANSACTION_ORDER_URL = "/api/v1/sealUnifyPay/querySealTrade";

	private static final String CARVING_ENTERPRISE_ORDER_HANDLE_URL = "/api/v1/sealUnifyPay/sealTradeHandle";

	private static final String REFUND_ORDER_HANDLE_URL = "/api/v1/sealUnifyPay/sealTradeRefunk";
	
	private static final String CLOSE_ORDER_RESULT_URL = "/api/v1/sealUnifyPay/closeTrade";

	/**
	 * 刻企订单处理接口
	 * 
	 * @param info
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public String CarvingEnterpriseOrderHandleInterface(SealTradeHandleVO info, String privateKey) throws Exception {
		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("密钥不能为空");
		}

		checkSealTradeHandleVO(info);

		String signed = SM2Util.sign(privateKey, info.toSign());
		info.setSigned(signed);
		return HttpUtils.doPostForIaip(_host, CARVING_ENTERPRISE_ORDER_HANDLE_URL, info.toString());
	}

	private void checkSealTradeHandleVO(SealTradeHandleVO info) {
		if (StringUtils.isBlank(info.getAppId())) {
			throw new RequestSystemException("应用编号不能为空");
		}
		if (StringUtils.isBlank(info.getTradeNo())) {
			throw new RequestSystemException("订单编号不能为空");
		}

		if (StringUtils.isBlank(info.getMakeOrganizeCode())) {
			throw new RequestSystemException("刻制企业统一社会信用代码不能为空");
		}
//		if (!StringUtils.equalsIgnoreCase("true", BusinessLicenseValidator.isCreditCode(info.getMakeOrganizeCode()))) {
//			throw new RequestSystemException("刻制企业统一社会信用代码,错误！");
//		}
		if (StringUtils.isBlank(info.getMakeOrganizeName())) {
			throw new RequestSystemException("刻制企业名称不能为空");
		}
		if (StringUtils.isBlank(info.getHandleStatus())) {
			throw new RequestSystemException("处理标识不能为空");
		}
		if (!"1,9".contains(info.getHandleStatus())) {
			throw new RequestSystemException("处理标识,错误！");
		}

	}

	/**
	 * 查询历史交易订单接口
	 * 
	 * @param info
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public String QueryHistoricalTransactionOrders(SealTradeQueryVO info, String privateKey) throws Exception {

		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("密钥不能为空");
		}

		checkSealTradeQueryVO(info);

		String signed = SM2Util.sign(privateKey, info.toSign());
		info.setSigned(signed);

		return HttpUtils.doPostForIaip(_host, QUERY_HISTORICAL_TRANSACTION_ORDER_URL, info.toString());
	}

	private void checkSealTradeQueryVO(SealTradeQueryVO info) {
		if (StringUtils.isBlank(info.getAppId())) {
			throw new RequestSystemException("应用编号不能为空");
		}
		if (StringUtils.isBlank(info.getTradeNo())) {
			throw new RequestSystemException("订单编号不能为空");
		}
		if (StringUtils.isBlank(info.getNotBeforeDate())) {
			throw new RequestSystemException("起始时间不能为空");
		}
		if (StringUtils.isBlank(info.getNotAfterDate())) {
			throw new RequestSystemException("结束时间不能为空");
		}
		if (StringUtils.isNotBlank(info.getPayOrganizeCode())) {
			if (!StringUtils.equalsIgnoreCase("true",
					BusinessLicenseValidator.isCreditCode(info.getPayOrganizeCode()))) {
				throw new RequestSystemException("申刻企业统一社会信用代码,错误！");
			}
		}

		if (StringUtils.isNotBlank(info.getMakeOrganizeCode())) {
			if (!StringUtils.equalsIgnoreCase("true",
					BusinessLicenseValidator.isCreditCode(info.getMakeOrganizeCode()))) {
				throw new RequestSystemException("制作组织统一社会信用代码 ,错误！");
			}
		}

	}

	/**
	 * 查询交易订单结果接口
	 * 
	 * @param info
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */

	public String QueryTransactionOrderResultInterface(SealTradeTrackVO info, String privateKey) throws Exception {

		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("私钥钥不能为空");
		}

		checkSealTradeTrackVO(info);

		String signed = SM2Util.sign(privateKey, info.toSign());
		// 将签名值放入对象中
		info.setSigned(signed);
		
		return HttpUtils.doPostForIaip(_host, QUERY_TRANSACTION_ORDER_RESULT_URL, info.toString());
	}

	private void checkSealTradeTrackVO(SealTradeTrackVO info) {
		if (StringUtils.isBlank(info.getAppId())) {
			throw new RequestSystemException("应用编号不能为空");
		}
		if (StringUtils.isBlank(info.getTradeNo())) {
			throw new RequestSystemException("订单编号不能为空");
		}
	}

	/**
	 * 创建印章交易订单接口
	 * 
	 * @param info
	 * @param privateKey
	 * @param gsPublicKey
	 * @return
	 * @throws Exception
	 */
	public String CreateSealTransactionOrderInterface(SealTradeMainInfoVO info, String privateKey, String gsPublicKey)
			throws Exception {

		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("密钥不能为空");
		}
		if (StringUtils.isBlank(gsPublicKey)) {
			throw new RequestSystemException("公钥不能为空");
		}

		checkSealTradeMainInfoVO(info);
		// 对数据做签名
		String signed = SM2Util.sign(privateKey, info.toSign());
		if (StringUtils.isBlank(signed)) {
			throw new RequestSystemException("数据签名异常");
		}
		// 将签名值放入对象中
		info.setSigned(signed);
		// 通过接口提交数据
		String result = HttpUtils.doPostForIaip(_host, CREATE_SEAL_TRANSACTION_ORDER_URL, info.toString());
		if (StringUtils.isBlank(result)) {
			throw new RequestSystemException("创建印章交易订单接口异常！");
		}
		// 校验返回数据的签名值
		JSONObject jo = (JSONObject) JSON.parse(result);
		String data = jo.getString("data");
		String resultSigned = jo.getString("sign");
		boolean ret = false;
		if(StringUtils.isNotBlank(data)) {
			ret = SM2Util.verify(gsPublicKey, data, resultSigned);
		}
		if (ret) {
			return result;
		} else {
			String msg = jo.getString("msg");
			throw new RequestSystemException("印章交易订单签名值异常:" + msg);
		}

	}

	private void checkSealTradeMainInfoVO(SealTradeMainInfoVO info) throws RequestSystemException {

		if (StringUtils.isBlank(info.getAppId())) {
			throw new RequestSystemException("应用编号不能为空");
		}

		if (StringUtils.isBlank(info.getTradeChannel())) {
			throw new RequestSystemException("交易通道不能为空");
		}

		if (!"wxpay,alipay,abcpay,app,helipay,wxappletpay".contains(info.getTradeChannel())) {
			throw new RequestSystemException("交易通道,添加错误！");
		}

		if (info.getTotalAmount() == null) {
			throw new RequestSystemException("交易金额(元)不能为空");
		}

		if (!NumUtils.isNumDecimal(info.getTotalAmount().toString())) {
			throw new RequestSystemException("交易金额(元)非数字！");
		}

		if (StringUtils.isBlank(info.getSubject())) {
			throw new RequestSystemException("订单标题不能为空");
		}

		if (StringUtils.isBlank(info.getPayOrganizeCode())) {
			throw new RequestSystemException("付费组织统一社会信用代码不能为空");
		}
		
//		if(!StringUtils.equalsAnyIgnoreCase("app", info.getTradeChannel())) {
//			if (!StringUtils.equalsIgnoreCase("true", BusinessLicenseValidator.isCreditCode(info.getPayOrganizeCode()))) {
//				throw new RequestSystemException("付费组织统一社会信用代码,错误！");
//			}
//		}

		if (StringUtils.isBlank(info.getPayOrganizeName())) {
			throw new RequestSystemException("付费组织名称不能为空");
		}

		if (info.getSealTradeDetailsInfoList() == null) {
			throw new RequestSystemException("商品明细不能为空");
		}

		if (StringUtils.isNotBlank(info.getMakeOrganizeCode())) {
			if (!StringUtils.equalsIgnoreCase("true",
					BusinessLicenseValidator.isCreditCode(info.getMakeOrganizeCode()))) {
				throw new RequestSystemException("制作组织统一社会信用代码 ,错误！");
			}
		}
	}

	/**
	 * 刻企退款处理接口
	 * 
	 * @param info
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public String RefundOrderHandleInterface(SealRefundHandleVO info, String privateKey) throws Exception {
		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("密钥不能为空");
		}

		checkSealRefundHandleVO(info);

		String signed = SM2Util.sign(privateKey, info.toSign());
		info.setSigned(signed);
		return HttpUtils.doPostForIaip(_host, REFUND_ORDER_HANDLE_URL, info.toString());
	}

	private void checkSealRefundHandleVO(SealRefundHandleVO info) {
		if (StringUtils.isBlank(info.getAppId())) {
			throw new RequestSystemException("应用编号不能为空");
		}
		if (StringUtils.isBlank(info.getTradeNo())) {
			throw new RequestSystemException("订单编号不能为空");
		}

//		if (StringUtils.isBlank(info.getGoodsIds())) {
//			throw new RequestSystemException("商品编号不能为空");
//		}
	}
	
	public boolean closeTradeOrder(SealTradeTrackVO tradeInfo, String privateKey) throws Exception {
		if (StringUtils.isBlank(privateKey)) {
			throw new RequestSystemException("私钥不能为空");
		}
		checkSealTradeTrackVO(tradeInfo);
		String signed = SM2Util.sign(privateKey, tradeInfo.toSign());
		//将签名值放入对象中
		tradeInfo.setSigned(signed);
		String result = HttpUtils.doPostForIaip(_host, CLOSE_ORDER_RESULT_URL, tradeInfo.toString());
		if (StringUtils.isBlank(result)) {
			throw new RequestSystemException("关闭交易订单接口异常!");
		}
		try {
			// 校验返回数据的签名值
			JSONObject jo = (JSONObject) JSON.parse(result);
			if (jo.containsKey("code") && jo.getIntValue("code") == 0) {
				return true;
			} else {
				throw new RequestSystemException(jo.getString("msg"));
			}
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
